package com.tos.controller;

import com.github.pagehelper.PageInfo;
import com.tos.pojo.*;
import com.tos.service.*;
import com.tos.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/flight")
public class FlightController {

    @Autowired
    private FlightService flightService;

    @Autowired
    private TicketService ticketService;

    @Autowired
    private SeatService seatService;

    @Autowired
    private CityService cityService;

    @Autowired
    private AirportService airportService;

    @Autowired
    private PassengerService passengerService;



    @RequestMapping("/getAirports")
    public List<String> getAirports(@RequestBody City city){
        System.out.println(city.getCity()+"1--------------------------------1");
        return airportService.getAirports(city.getCity());
    }

    @RequestMapping("/getFlight/{id}")
    public Flight getFlight(@PathVariable("id") Integer id){
        System.out.println("执行了getFlight");
        return flightService.getFlight(id);
    }



    @RequestMapping("/loadCity")
    public List<String> loadCity(){
        return cityService.getCities();
    }

    // 多个查询(分页）,由于时间问题，只搞了首页航班查询的分页
    @RequestMapping("/queryFlightByPassenger")
    public PageInfo<Flight> getFlights(@RequestParam(defaultValue="",value = "srcCity") String srcCity, @RequestParam(defaultValue="",value = "dstCity") String dstCity,
                                            @RequestParam(defaultValue="",value = "queryDate") String queryDateStr, @RequestParam(required = false,defaultValue="1",value="pageNum") int pageNum,
                                               @RequestParam(defaultValue="5",value="pageSize") int pageSize, HttpServletRequest request) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        boolean isManager = false;
        //判断是否是管理员查询航班
        if (request.getSession().getAttribute(Constants.MANAGER_SESSION) != null) {
            isManager = true;
        }
        Date queryDate = null;
        if (!"".equals(queryDateStr) && queryDateStr != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            queryDate = simpleDateFormat.parse(queryDateStr);
        }
        map.put("isManager",isManager);
        map.put("srcCity",srcCity);
        map.put("dstCity",dstCity);
        map.put("queryDate",queryDate);
        List<String> cityList = cityService.getCities();
        request.setAttribute("cityList",cityList);
        request.setAttribute("srcCity",srcCity);
        request.setAttribute("dstCity",dstCity);
        request.setAttribute("queryDate",queryDate);

        return flightService.flightPageQuery(map,pageNum,pageSize);
    }

    @RequestMapping("/getFlightsByPassenger")
    public List<Flight> queryFlightByPassenger(@RequestBody QueryCondition queryCondition)  {
        HashMap<String, Object> map = new HashMap<>();


        System.out.println("srcCity = " + queryCondition.getSrcCity());
        System.out.println("dstCity = " + queryCondition.getDstCity());
        System.out.println("queryCondition.getStartTime() = " + queryCondition.getStartTime());
        System.out.println("isManager = " + queryCondition.getIsManager());



        Date queryDate = null;
//        if (!"".equals(queryCondition.getStartTime()) && queryCondition.getStartTime() != null) {
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//            try {
//                queryDate = simpleDateFormat.parse(queryCondition.getStartTime());
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//        }

        map.put("isManager",Boolean.valueOf(queryCondition.getIsManager()));
        map.put("srcCity",queryCondition.getSrcCity());
        map.put("dstCity",queryCondition.getDstCity());
        map.put("queryDate",queryCondition.getStartTime());

        List<Flight> flightList = flightService.getFlights(map);
        List<String> cityList = cityService.getCities();
        for(Flight flight : flightList) {
            if(flight.getSize()==1){
                flight.setSizeStr("小型机");
            }
            else{
                if(flight.getSize()==2){
                    flight.setSizeStr("中型机");
                }
                else{
                    flight.setSizeStr("大型机");
                }
            }
            System.out.println(flight);
        }

        return flightList;
    }


    @RequestMapping("/test/{id}")
    public String testBook(@PathVariable("id") Integer id){
        System.out.println("id = " + id);
        return "执行了getFlight";
    }


    @RequestMapping("/bookFlight/{flightId}/{seatType}/{passengerId}")
    public String bookFlight(@PathVariable("flightId") Integer flightId,@PathVariable("seatType") Integer seatType,@PathVariable("passengerId") Integer passengerId){
        Ticket ticket = new Ticket();
        System.out.println("flightId = " + flightId);
//        System.out.println("passengerId = " + passengerId);
        //生成机票的各种信息
        System.out.println("seatType = " + seatType);
//
        Passenger passenger =passengerService.getPassengerById(passengerId);
        System.out.println(passenger.toString());
//        if (passenger == null) {
//            request.setAttribute("error","请登录!");
//            return "login_reg";
//        }

        //System.out.println(flightId + " " +seatType);

        HashMap<String, Object> map = new HashMap<>();
        map.put("flightId",flightId);
        map.put("seatType",seatType);

        String ticketId = UUID.randomUUID().toString().trim().replaceAll("-", "");
        String seatId = seatService.getSeatId(map);
        if(seatId==null||seatId==""){

            return "noTicket";
        }
        System.out.println(seatId);
        Flight flight = flightService.getFlight(flightId);

        long halfHour = 30*60*1000;
        Date boardTime = new Date(flight.getStartTime().getTime() - halfHour);

        //打包
        ticket.setTicketId(ticketId);
        ticket.setFlightId(flightId);
        ticket.setSeatId(seatId);
        ticket.setDepartureTime(flight.getStartTime());
        ticket.setBoardTime(boardTime);
        ticket.setCardId(passenger.getCardId());

        boolean success = ticketService.bookFlight(ticket);
        if (success) {
            System.out.println("ticket.toString() = " + ticket.toString());
            return "success";
        }else {
            return "fail";
        }

    }

    @RequestMapping("/insertFlight")
    public String insertFlight(@RequestBody Flight flight)  {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        System.out.println(flight.toString());

        if(flightService.insertFlight(flight)) {

            return "success";
        }
        return "fail";
    }
    @RequestMapping("/deleteFlight/{id}")
    public String deleteFlight(@PathVariable("id") Integer id){
        if(flightService.deleteFlight(id)){
            return "success";
        }
        return "fail";
    }
    @RequestMapping("/updateFlight")
    public String updateFlight(@RequestBody Flight flight){
        System.out.println(flight.toString());
        if(flightService.updateFlight(flight)){
            return "success";
        }
        return "fail";
    }

    @RequestMapping("/flightStatistics")
    public List<Flight> flightStatistics(@RequestBody SummaryCondition summaryCondition) {

        HashMap<String, Object> map = new HashMap<>();


        map.put("airline",summaryCondition.getAirline());
        map.put("srcCity",summaryCondition.getSrcCity());
        map.put("dstCity",summaryCondition.getDstCity());
        map.put("statisticsTime",summaryCondition.getSummaryTime());
        List<Flight> flightBeans = flightService.flightStatistics(map);


        if(flightBeans.size()>0){
            System.out.println("有统计数据");
        }
       return flightBeans;

    }
}
